package corej.prj.chatRoom.Dan;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ChatServer {

    public static void main(String[] args) {

        List<Socket> sockets = new ArrayList<Socket>();

        ServerSocket ss = null;

        try {
            ss = new ServerSocket(9000);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (true) {
            try {
                Socket s;
                s = ss.accept();
                sockets.add(s);
                // Thread
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

class ServerThread extends Thread {
    private Socket s;

    private List<Socket> sockets;

    public ServerThread(Socket s, List<Socket> sockets) {
        super();
        this.s = s;
        this.sockets = sockets;
    }

    public void run() {
        try {
            InputStream is = s.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(is));

            while (true) {
                String message = in.readLine();
                if (message != null) {
                    for (int i = 0; i < sockets.size(); i++) {
                        OutputStream os = ((Socket) sockets.get(i))
                                .getOutputStream();
                        PrintWriter out = new PrintWriter(os, true);
                        out.println(message);
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}